const redis = require("redis")

let redisConf = require("./dbconfig")

class redisCon {
  public redisClient: any
  constructor() {
    this.redisClient = redis.createClient(redisConf.REDIS_CONF.port, redisConf.REDIS_CONF.host)
    this.redisClientErr()
  }
  redisClientErr() {
    this.redisClient.on("err", (err:any) => {
      console.log(err);

    })
  }
  set(key:string, val:any, time:number=0) {
    // 不要直接将object类型的数据存到redis 会有问题
    if (typeof val === "object") {
      val = JSON.stringify(val)
    }
    this.redisClient.set(key, val, redis.print)
    if(time>0){
    this.redisClient.expire(key,time)
    }
  }
  del(key:string){
    if(this.redisClient.exists){
    this.redisClient.del(key)
    }
  }
  get(key:string) {
    return new Promise((resolve, reject) => {
      this.redisClient.get(key, (err:any, val:any) => {
        if (err) {
          reject(err)
        } else {
          if (val == null) {
            resolve(null)
          }
        typeof val === 'object'?resolve(val):resolve(JSON.parse(val))
        }
      })
    })
  }
}

export default new redisCon()